package com.yxt.qmgf.number.ctrl;

import com.yxt.qmgf.number.service.sudokuService;
import com.yxt.qmgf.number.view.sudokuView;
import com.yxt.qmgf.number.vo.GameConfig;
import com.yxt.qmgf.number.vo.GameState;
import com.yxt.qmgf.number.vo.ScoreRecord;
import com.yxt.qmgf.shop.ctrl.ShopController;
import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class numberController implements Initializable {
    private UserInfoVO vo;
    private sudokuService sudokuService;
    private sudokuView sudokuView;
    private Timeline timer;
    private Stage gameStage; // 新增：用于保存游戏窗口
    private int secondsElapsed = 0;

    @FXML private GridPane gameGrid;
    @FXML private ComboBox<String> difficultyComboBox;
    @FXML private Label timeLabel;
    @FXML private Label mistakesLabel;
    @FXML private Label messageLabel;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        sudokuService = new sudokuService();

        // 初始化难度选择
        difficultyComboBox.getItems().addAll(
                "简单 (推荐新手)",
                "中等 (常规挑战)",
                "困难 (高手难度)"
        );
        difficultyComboBox.getSelectionModel().selectFirst();
    }

    public void setUser(UserInfoVO vo) {
        this.vo = vo;
    }

    @FXML
    public void startGame() {
        try {
            int difficulty = difficultyComboBox.getSelectionModel().getSelectedIndex() + 1;
            GameConfig config = new GameConfig(difficulty);

            // 创建新窗口
            gameStage = new Stage();

            // 加载游戏FXML（使用绝对路径）
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/number/SudukuGame.fxml"));
            Parent root = loader.load();

            // 获取游戏控制器并初始化游戏
            SudokuGameController gameController = loader.getController();
            gameController.initGame(config, vo, gameStage);

            // 设置场景并显示窗口
            Scene scene = new Scene(root);
            gameStage.setScene(scene);
            gameStage.setTitle("数独游戏 - " + difficultyComboBox.getValue());
            gameStage.setOnCloseRequest(e -> {
                gameStage = null;
            });
            gameStage.show();

        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "启动游戏失败", "无法加载游戏界面: " + e.getMessage());
        }
    }

    private void showAlert(String title, String header, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(header);
        alert.setContentText(content);
        alert.showAndWait();
    }

    private void setupCellHandlers() {
        TextField[][] cells = sudokuView.getCells();
        GameState gameState = sudokuService.getCurrentGame();
        int[][] solution = gameState.getSolution();

        for (int row = 0; row < 9; row++) {
            for (int col = 0; col < 9; col++) {
                TextField cell = cells[row][col];
                if (cell.isEditable()) {
                    final int r = row;
                    final int c = col;

                    cell.setOnAction(e -> {
                        String text = cell.getText();
                        if (!text.isEmpty()) {
                            int num = Integer.parseInt(text);
                            if (num == solution[r][c]) {
                                // 答案正确
                                gameState.getBoard()[r][c] = num;
                                cell.setEditable(false);
                                cell.setStyle(sudokuView.getCellStyle(r, c) + "-fx-font-weight: bold; -fx-background-color: #e6ffe6;");

                                // 检查游戏是否完成
                                if (sudokuService.isGameComplete(gameState.getBoard())) {
                                    gameCompleted(gameState);
                                }
                            } else {
                                // 答案错误
                                gameState.incrementMistakes();
                                mistakesLabel.setText("错误: " + gameState.getMistakes());
                                cell.setStyle(sudokuView.getCellStyle(r, c) + "-fx-background-color: #ffe6e6;");
                            }
                        }
                    });
                }
            }
        }
    }

    private void gameCompleted(GameState gameState) {
        timer.stop();
        messageLabel.setText("恭喜完成游戏！");

        // 保存分数记录
        sudokuService.saveScore(vo,
                difficultyComboBox.getSelectionModel().getSelectedIndex() + 1,
                secondsElapsed,
                gameState.getMistakes()
        );

        // 显示完成消息
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("游戏完成");
        alert.setHeaderText("恭喜您完成数独游戏！");
        alert.setContentText(String.format(
                "难度: %s\n用时: %d秒\n错误次数: %d",
                difficultyComboBox.getValue(),
                secondsElapsed,
                gameState.getMistakes()
        ));
        alert.showAndWait();
    }

    private void updateTimeLabel() {
        int minutes = secondsElapsed / 60;
        int seconds = secondsElapsed % 60;
        timeLabel.setText(String.format("用时: %02d:%02d", minutes, seconds));
    }

    @FXML
    public void rule() {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("数独规则");
        alert.setHeaderText("数独游戏规则");
        alert.setContentText("1. 在9×9的格子中填入数字1-9\n" +
                "2. 每一行必须包含1-9且不重复\n" +
                "3. 每一列必须包含1-9且不重复\n" +
                "4. 每个3×3宫格必须包含1-9且不重复\n" +
                "5. 游戏开始时部分格子已填好数字\n" +
                "6. 目标是用最短时间和最少错误完成游戏");
        alert.showAndWait();
    }

    @FXML
    public void jifen() {
        List<ScoreRecord> userScores = sudokuService.getUserScores(vo.getUsername());
        List<ScoreRecord> scoreboard = sudokuService.getScoreboard();

        StringBuilder content = new StringBuilder();
        content.append("=== 您的游戏记录 ===\n");
        if (userScores.isEmpty()) {
            content.append("暂无游戏记录\n");
        } else {
            for (int i = 0; i < Math.min(userScores.size(), 5); i++) {
                ScoreRecord record = userScores.get(i);
                content.append(String.format("%d. %s - %d秒 - %d分 (%s)\n",
                        i+1,
                        record.getDifficultyName(),
                        record.getTime(),
                        record.getScore(),
                        record.getFormattedTime()));
            }
        }

        content.append("\n=== 排行榜 ===\n");
        if (scoreboard.isEmpty()) {
            content.append("暂无排行榜数据\n");
        } else {
            for (int i = 0; i < scoreboard.size(); i++) {
                ScoreRecord record = scoreboard.get(i);
                content.append(String.format("%d. %s - %d分 (%s)\n",
                        i+1,
                        record.getName(),
                        record.getScore(),
                        record.getDifficultyName()));
            }
        }

        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("成绩记录");
        alert.setHeaderText("游戏成绩和排行榜");
        alert.setContentText(content.toString());
        alert.getDialogPane().setMinWidth(400);
        alert.showAndWait();
    }

    @FXML
    public void buy() {
        try {
            // 加载购买页面的FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/shop/Shop.fxml"));
            Parent root = loader.load();

            // 获取购买页面的控制器实例
            ShopController shopController = loader.getController();

            // 创建新的Stage并设置Scene
            Stage stage = new Stage();
            stage.setTitle("购买页面");
            stage.setScene(new Scene(root));
            // 如果需要模态展示，可添加以下代码
            stage.initModality(Modality.APPLICATION_MODAL);

            // 展示购买页面
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void back() {
        if (timer != null) {
            timer.stop();
        }
        // 关闭当前窗口的逻辑
    }

    public void setOff(UserInfoVO vo) {
        this.vo = vo;
    }
}